package com.mediacenter.activity;

import io.vov.vitamio.Vitamio;

import java.lang.reflect.Method;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.View;
import android.view.View.OnFocusChangeListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageButton;
import android.widget.LinearLayout;

import com.mediacenter.R;
import com.mediacenter.adapter.ContentShowAdapter;
import com.mediacenter.application.MApplication;
import com.mediacenter.site.model.Show;
import com.mediacenter.site.model.Source;
import com.mediacenter.widget.ProgressManager;
import com.naduolai.android.app.FlagUpdateManager;
import com.naduolai.android.ui.guide.SingleGuideView;
import com.naduolai.android.util.SystemUtil;
import com.ndjh.ormlite.NDJHBaseDao;
import com.umeng.analytics.MobclickAgent;

public class CollectActivity extends Activity {

	private GridView tableContentGridView;

	private List<Show> collectionShows, searchResultShows, historyShows;
	
	private ContentShowAdapter superAdapter;

	private MApplication application;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		application = MApplication.getInstance();
		ProgressManager.getInstance().setActivity(this);
		tableContentGridView = (GridView) findViewById(R.id.table_content_gridView);
		
		superAdapter = new ContentShowAdapter(this, tableContentGridView);
		tableContentGridView.setAdapter(superAdapter);
		tableContentGridView.setOnItemSelectedListener(new OnItemSelectedListener() {
			@Override
			public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
				android.util.Log.e(getClass().getName(), "position:"+position);
				android.util.Log.e(getClass().getName(), "hello");
				ListActivity.scaleAnim(CollectActivity.this, parent, view);
				ListActivity.setSelectBackground(parent, view);
			}
			@Override
			public void onNothingSelected(AdapterView<?> parent) {}
		});
		
		tableContentGridView.setOnItemClickListener(siteListOnItemClickListener);
		tableContentGridView.setOnFocusChangeListener(onFocusChangeListener);
		
//11		Button button = (Button) findViewById(R.id.source_list);
		Button button = (Button) findViewById(getIntent().getExtras().getInt("ID", R.id.play_record));
//		Button button = (Button) findViewById(R.id.play_record);
		button.performClick();
		button.requestFocus();
		button.requestLayout();
		
		findViewById(R.id.search_edittext).setOnFocusChangeListener(new OnFocusChangeListener() {
			@Override
			public void onFocusChange(View v, boolean hasFocus) {
				if (hasFocus) {
					android.util.Log.e(getClass().getName(), "打开软键盘");
					InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
					inputMethodManager.showSoftInput(v, InputMethodManager.SHOW_FORCED);
				}
			}
		});
		
 		findViewById(getIntent().getExtras().getInt("ID", R.id.play_record)).setBackgroundResource(R.drawable.menu_focus);
		//findViewById(R.id.play_record).setBackgroundResource(R.drawable.menu_focus);
//		MobclickAgent.onError(this);
		
		/****************** 使用向导 **************/
//		Integer[] guide_resource = new Integer[] { R.drawable.guide1, R.drawable.guide2,
//				R.drawable.guide3, R.drawable.guide4, R.drawable.guide5 };
//		int width = FULL_SCREEN_WIDTH;
//		int height = FULL_SCREEN_HEIGHT;
//		float wscale = 1.f;
//		float hscale = 1.f;
//		if (width != BaseActivity.DEFAULT_FULL_SCREEN_WIDTH && height != BaseActivity.DEFAULT_FULL_SCREEN_HEIGHT) {
//			wscale = width * 1.f / BaseActivity.DEFAULT_FULL_SCREEN_WIDTH;
//			hscale = height * 1.f / BaseActivity.DEFAULT_FULL_SCREEN_HEIGHT;
//		}
//		Rect[] guide_rect = new Rect[] { 
//				new Rect((int) (686 * wscale), (int) (294 * hscale), 10, 10),
//				new Rect((int) (723 * wscale), (int) (326 * hscale), 10, 10), 
//				new Rect((int) (450 * wscale), (int) (227 * hscale), 10, 10),
//				new Rect((int) (600 * wscale), (int) (220 * hscale), 10, 10), 
//				new Rect((int) (630 * wscale), (int) (210 * hscale), 10, 10) };
		SingleGuideView singleGuideView = new SingleGuideView(this, null, null, ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE);
		singleGuideView.showAppGuideView(true);
		/******************使用向导end**************/
		
		/****************** 软件版本检查 **************/
//		if (checkNetworkAvailable()) {
//			// 版本更新检查
//			FlagUpdateManager flagUpdateManager = FlagUpdateManager.getInstance();
//			flagUpdateManager.checkUpadatePackage(this, Constants.APP_CODE, SystemUtil.getAppVersionName(this));
//			// 设置DownloadDialog显示的位置
//			flagUpdateManager.showDownloadDialog(this);
//			// 设置UpdateDialog显示的位置
//			flagUpdateManager.showUpdateDialog(this);
//			// flagUpdateManager.getInstance().
//		}
		/****************** 软件版本检查end **************/
		
		new Thread() {
			public void run() {
				try {
					Vitamio.initialize(CollectActivity.this);
				} catch (Exception e) {
					// TODO: handle exception
				}
			};
		}.start();
	}
	/**
	 * 判断网络是否可用
	 * 
	 * @return
	 */
//	protected boolean checkNetworkAvailable() {
//		boolean flag = false;
//		ConnectivityManager cwjManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
//		if (cwjManager.getActiveNetworkInfo() != null) {
//			flag = cwjManager.getActiveNetworkInfo().isAvailable();
//		}
//		return flag;
//	}

	public static void resetSelect(View view) {
		try {  
            @SuppressWarnings("unchecked")  
            Class<GridView> c = (Class<GridView>) Class.forName("android.widget.GridView");  
            Method[] flds = c.getDeclaredMethods();  
            for (Method f : flds) {  
                if ("setSelectionInt".equals(f.getName())) {  
                    f.setAccessible(true);  
                    f.invoke(view,new Object[] { Integer.valueOf(-1) });  
                }  
            }  
        } catch (Exception e) {  
            e.printStackTrace();  
        }
	}

	@Override
	protected void onResume() {
		super.onResume();
		resetSelect(tableContentGridView);
		try {
			if (superAdapter.getShows() == collectionShows) {
				NDJHBaseDao<Show, Integer> showdao = application.getHelper().getShowDao();
				collectionShows = showdao
						.queryAllData("select * from Show where collected = 1 order by collectedTime desc;");
				superAdapter.setShows(collectionShows);
				superAdapter.notifyDataSetChanged();
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
		
		try {
			if (superAdapter.getShows() == historyShows) {
				NDJHBaseDao<Show, Integer> showdao = application.getHelper().getShowDao();
				historyShows = showdao
						.queryAllData("select * from Show where lastPlayTime > 0 order by lastPlayTime desc limit 0,20;");
				superAdapter.setShows(historyShows);
				superAdapter.notifyDataSetChanged();
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
	
	OnItemSelectedListener onItemSelectedListener = new OnItemSelectedListener() {
		@Override
		public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
			ListActivity.scaleAnim(CollectActivity.this, parent, view);
			ListActivity.setSelectBackground(parent, view);
		}
		@Override
		public void onNothingSelected(AdapterView<?> parent) {
			
		}
	};
	
	View.OnFocusChangeListener onFocusChangeListener = new View.OnFocusChangeListener() {  
        @Override  
        public void onFocusChange(View v, boolean hasFocus) {  
            if (!hasFocus) {  
            	resetSelect(v);
            }  
        }  
    };

	OnItemClickListener siteListOnItemClickListener = new OnItemClickListener() {
		@Override
		public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
			Source source = application.getSources().get(position);
			application.setCurrentSource(source);
			// 从这里入口
			Intent intent = new Intent(CollectActivity.this, ListActivity.class);
			startActivity(intent);
			//各个站点的进入次数
			MobclickAgent.onEvent(CollectActivity.this, "WEBSITE_ENTER_COUNT", source.getSourceThumb());
		}
	};

	OnItemClickListener collectionListOnItemClickListener = new OnItemClickListener() {
		@Override
		public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
			if (collectionShows == null) {
				return;
			}
			application.setCurrentSource(collectionShows.get(position).getSourceName());
			application.setCurrentShow(collectionShows.get(position));
			// 从这里入口
			Intent intent = new Intent(CollectActivity.this, DetailsActivity.class);
			startActivity(intent);
		}
	};
	
	OnItemClickListener searchOnItemClickListener = new OnItemClickListener() {
		@Override
		public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
			if (searchResultShows == null) {
				return;
			}
			application.setCurrentSource(searchResultShows.get(position).getSourceName());
			application.setCurrentShow(searchResultShows.get(position));
			// 从这里入口
			Intent intent = new Intent(CollectActivity.this, DetailsActivity.class);
			startActivity(intent);
		}
	};
	
	OnItemClickListener historyOnItemClickListener = new OnItemClickListener() {
		@Override
		public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
			if (historyShows == null) {
				return;
			}
			application.setCurrentSource(historyShows.get(position).getSourceName());
			application.setCurrentShow(historyShows.get(position));
			// 从这里入口
			Intent intent = new Intent(CollectActivity.this, DetailsActivity.class);
			startActivity(intent);
		}
	};

	private ExecutorService executorService;

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.activity_main, menu);
		return true;
	}

	public void click(View v) {
		LinearLayout leftLayout = (LinearLayout) findViewById(R.id.left_navigation);
		for (int i = 0; i < leftLayout.getChildCount(); i++) {
			if (leftLayout.getChildAt(i) instanceof Button) {
				if (leftLayout.getChildAt(i) == v) {
					leftLayout.getChildAt(i).setBackgroundResource(R.drawable.menu_focus);
				}else {
					leftLayout.getChildAt(i).setBackgroundResource(R.drawable.menu_selector);
				}
			}
		}
		SystemUtil.hiddenSoftInput(this, v);
		findViewById(R.id.search_area).setVisibility(View.INVISIBLE);
		resetSelect(tableContentGridView);
		switch (v.getId()) {
		/*case R.id.source_list:
			tableContentGridView.setOnItemClickListener(siteListOnItemClickListener);
			superAdapter.setShows(application.getSourceShows());
			superAdapter.notifyDataSetChanged();
			break;*/
		case R.id.play_collection:
			tableContentGridView.setOnItemClickListener(collectionListOnItemClickListener);
			try {
				NDJHBaseDao<Show, Integer> showdao = application.getHelper().getShowDao();
				collectionShows = showdao
						.queryAllData("select * from Show where collected = 1 order by collectedTime desc;");
				superAdapter.setShows(collectionShows);
				superAdapter.notifyDataSetChanged();
			} catch (SQLException e) {
				e.printStackTrace();
			}
			break;
		case R.id.play_record:
			tableContentGridView.setOnItemClickListener(historyOnItemClickListener);
			try {
				NDJHBaseDao<Show, Integer> showdao = application.getHelper().getShowDao();
				historyShows = showdao
						.queryAllData("select * from Show where lastPlayTime > 0 order by lastPlayTime desc limit 0,20;");
				superAdapter.setShows(historyShows);
				superAdapter.notifyDataSetChanged();
			} catch (SQLException e) {
				e.printStackTrace();
			}
			break;
		case R.id.super_search:
			findViewById(R.id.search_area).setVisibility(View.VISIBLE);
			EditText editText = (EditText)findViewById(R.id.search_edittext);
			editText.setOnKeyListener(new View.OnKeyListener() {              
		        @Override  
		        public boolean onKey(View v, int keyCode, KeyEvent event) {
		        	if (KeyEvent.KEYCODE_ENTER == keyCode) {
		        		ImageButton button = (ImageButton) findViewById(R.id.search_button);
		        		button.performClick();
					}
		            return false;  
		        }  
		    });
			tableContentGridView.setOnItemClickListener(searchOnItemClickListener);
			superAdapter.setShows(searchResultShows);
			superAdapter.notifyDataSetChanged();
			break;
		case R.id.search_button:
			findViewById(R.id.search_area).setVisibility(View.VISIBLE);
			if (executorService == null || executorService.isShutdown()) {
				executorService = Executors.newSingleThreadExecutor();
			}
			findViewById(R.id.search_button).setEnabled(false);
			final String editTextString = ((EditText)findViewById(R.id.search_edittext)).getText().toString().trim();
			((EditText)findViewById(R.id.search_edittext)).setText(editTextString);
			ProgressManager.getInstance().showProcessDialog("loading...");
			Thread thread = new Thread() {
				@Override
				public void run() {
					final List<Show> shows = new ArrayList<Show>();
					try {
						List<Source> sources = MApplication.getInstance().getSources();
						for (Source source : sources) {
							List<Show> sourceShows = source.search(editTextString);
							if (sourceShows == null) {
								continue;
							}
							Source.dbFormat(sourceShows, source.getSourceThumb());
							shows.addAll(sourceShows);
						}
						// 搜索了那些内容
						MobclickAgent.onEvent(CollectActivity.this, "VIDEO_SEARCH_COUNT", editTextString);
					} catch (Exception e) {
						e.printStackTrace();
					} finally {
						runOnUiThread(new Runnable() {
							@Override
							public void run() {
								resetSelect(tableContentGridView);
								searchResultShows = shows;
								superAdapter.setShows(searchResultShows);
								superAdapter.notifyDataSetChanged();
								findViewById(R.id.search_button).setEnabled(true);
								ProgressManager.getInstance().cancel();
							}
						});
					}
				}
			};
			thread.setPriority(Thread.MIN_PRIORITY);
			executorService.submit(thread);
			break;
		default:
			break;
		}
	}

	@Override
	protected void onStop() {
		superAdapter.cleanCache();
		super.onStop();
	}
 
	@Override
	protected void onDestroy() {
//		FlagUpdateManager.getInstance().startSilentInstall(this);
		super.onDestroy();
	}
	
	@Override
	public void onLowMemory() {
		super.onLowMemory();
		if (superAdapter != null) {
			superAdapter.cleanCache();
		}
	}
}
